//
//  QuoteListVC.m
//  zhiche--delivery
//
//  Created by 王亚陆 on 16/6/1.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "QuoteListVC.h"
#import "Common.h"
#import "QuoteCell.h"
#import "QuoteListCell.h"
#import <Masonry.h>
#import "ConfirmOrder.h"
#import "PayVC.h"
#import <MJRefresh.h>
#import "WKProgressHUD.h"
#import "RLNetworkHelper.h"
#import "Earnest_PayViewController.h"
#import "NullView.h"

#define tableTag  1000
#define quoteTableTag 2000
@interface QuoteListVC ()
{
    UIView * nav;
    UITableView * quoteTable;
    NSMutableArray * dataSouceArr;
    NSMutableDictionary * dataSouceDic;
    int page;
    int totalPage;
    UIView * NoNetWorkView;
    WKProgressHUD *hud;
    Common *Com;
    NullView * nullView;

}
@end

@implementation QuoteListVC
- (instancetype)init

{
    self = [super init];
    if (self) {
        self.orderID = [[NSString alloc]init];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    nav = [self createNav:@"报价列表"];
    [self.view addSubview:nav];
    Com = [[Common alloc]init];

    page = 1;
    totalPage = 1;
    self.view.backgroundColor = [UIColor whiteColor];
    dataSouceArr = [[NSMutableArray alloc]init];
    dataSouceDic = [[NSMutableDictionary alloc]init];
    [self createTable];
    
    //无网路状态和加载状态
    [self createNetWorkAndStatue];
    nullView = [[NullView  alloc]initWithFrame:CGRectMake(0, (178)*kHeight, screenWidth, screenHeight - (178)*kHeight ) andTitle:@"暂无报价"];
    nullView.backgroundColor = GrayColor;
    nullView.label.text = @"暂无报价";
}

-(void)createNetWorkAndStatue{
    //创建无网络状态view
    NoNetWorkView = [Com noInternet:@"无网啊" and:self action:@selector(NoNetPressBtn) andCGreck:CGRectMake(0, 0, Main_Width, Main_height-64)];
    [quoteTable addSubview:NoNetWorkView];
    //判断是否有网
    [self judgeNetWork];
    //创建加载状态
    hud = [WKProgressHUD showInView:self.view withText:@"加载中" animated:YES];
}

//判断是否有网
-(void)judgeNetWork{
    if (![RLNetworkHelper isConnectedToNetwork]) {
        NoNetWorkView.hidden = NO;
    }
    else{
        NoNetWorkView.hidden = YES;
        [self createData];
    }
}

//无网络状态
-(void)NoNetPressBtn{
    if ([RLNetworkHelper isConnectedToNetwork]) {
        NoNetWorkView.hidden = YES;
        [self createData];
    }
}

-(void)createTable{
    
    quoteTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, Main_Width,Main_height-64) style:UITableViewStylePlain];
    [quoteTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    quoteTable.delegate = self;
    quoteTable.dataSource = self;
    quoteTable.tag = quoteTableTag;
    quoteTable.backgroundColor = GrayColor;
    quoteTable.showsHorizontalScrollIndicator = NO;
    quoteTable.showsVerticalScrollIndicator = NO;
    [quoteTable.mj_header beginRefreshing];
    quoteTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    quoteTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    [self.view addSubview:quoteTable];
}

-(void)downRefresh{
    
    [quoteTable.mj_header endRefreshing];
    [quoteTable.mj_footer endRefreshing];
    page = 1;
    [self createData];
    NSLog(@"刷新");
}
-(void)upRefresh{
    
    if (page!=totalPage) {
        page ++;
        [self createData];
        [quoteTable.mj_footer endRefreshing];
    }else{
        quoteTable.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [quoteTable.mj_header endRefreshing];
    NSLog(@"加载%d%d",page,totalPage);
    
}

-(void)createData{
    
//    Order_Quote_Url orderid
    NSLog(@"%@",Order_Quote_Url);
    int pageSize = 10;
//http://192.168.199.199:8080/kyle/quote/list/30?pageNo=1&pageSize=10

    NSString * string = [NSString stringWithFormat:@"%@%@?pageNo=%d&pageSize=%d",Order_Quote_Url,self.orderID,page,pageSize];
    
    [Common requestWithUrlString:string contentType:@"application/json" finished:^(id responseObj){
        
        dataSouceDic = responseObj[@"data"];
//        dataSouceArr = dataSouceDic[@"order"][@"quotes"];
        
        NSMutableArray * arr = [NSMutableArray arrayWithArray:dataSouceDic[@"order"][@"quotes"]];
        if ([arr count]>0) {

            [nullView removeFromSuperview];
            if (page == 1) {
                [dataSouceArr removeAllObjects];
                dataSouceArr = arr;
            }else{
                for (int i=0; i<[arr count]; i++) {
                    
                    [dataSouceArr addObject:arr[i]];
                }
            }
        }else{
            [dataSouceArr removeAllObjects];
            [quoteTable addSubview:nullView];
        }

        
        totalPage = [dataSouceDic[@"page"][@"totalPage"] intValue];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [hud dismiss:YES];
            [quoteTable reloadData];
        });

    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [hud dismiss:YES];
    });

}

-(void)viewWillAppear:(BOOL)animated{
    
    
    [self createData];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *str=@"str";
    if (indexPath.row == 0) {
        //运单cell
        QuoteCell * cell =  [tableView dequeueReusableCellWithIdentifier:str];
        if (cell ==nil) {
            cell = [[QuoteCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (dataSouceDic.allKeys.count !=0) {
            [cell showInfo:dataSouceDic[@"order"]];
        }
        cell.Btn2.hidden = YES;
//        cell.Btn3.hidden = YES;
        cell.price.hidden = YES;
        cell.view.frame =CGRectMake(0, 0, Main_Width, 178*kHeight);
        return cell;
    }else{
        QuoteListCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
        if (cell == nil) {
            
            cell = [[QuoteListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
        [cell showInfo:dataSouceArr[indexPath.row-1]];
        cell.QutoteBtn.indexpath = indexPath;
        [cell.QutoteBtn addTarget:self action:@selector(pressQutoteBtn:) forControlEvents:UIControlEventTouchUpInside];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

-(void)pressQutoteBtn:(NewBtn*)sender{
    
    Earnest_PayViewController * confirm = [[Earnest_PayViewController alloc]init];

    confirm.quoteid = dataSouceArr[sender.indexpath.row-1][@"id"];
    confirm.orderId = dataSouceDic[@"order"][@"id"];
    [self.navigationController pushViewController:confirm animated:YES];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  (indexPath.row == 0)?178*kHeight:163*kHeight;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
//    return dataSouceArr.count;
    return (dataSouceArr.count>0)?(1+dataSouceArr.count):1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createUIAlertController:(NSString*)title

{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}



@end
